//
//  GKOauthViewController.swift
//  MicroBlogFunc
//
//  Created by GK on 16/4/9.
//  Copyright © 2016年 GK. All rights reserved.
//

import UIKit
import SVProgressHUD

class GKOauthViewController: UIViewController {

    override func loadView() {
        self.view = self.webView
        self.webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //背景色
        self.view.backgroundColor = globalBgColor
        //导航栏按钮
        self.setBBI()
        //加载webView
        let url = oauthURL()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
        //指示器效果
        SVProgressHUD.showErrorWithStatus("正在加载....")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
        
        
    }
    
    //获取url
    private func oauthURL() -> NSURL
    {
        let urlStr = OauthURL + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        return NSURL(string: urlStr)!
    }
    
    
    //设置导航栏按钮
    private func setBBI(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(self.filledCode))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(self.cancel))
    }
    
    //导航栏按钮监听
    @objc private func filledCode(){
//        GKPrint("filledCode")
        let js = "document.getElementById('userId').value = '18507564582';document.getElementById('passwd').value = 'kingago1947175'"
        self.webView.stringByEvaluatingJavaScriptFromString(js)
    }
    @objc private func cancel(){
        SVProgressHUD.dismiss()
        self.dismissViewControllerAnimated(true, completion: nil)
    }

    
    
    
    //懒加载
    private lazy var webView:UIWebView = UIWebView()
    
}

//分类实现webviewdelete
extension GKOauthViewController:UIWebViewDelegate
{   //是否去加载一个请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        let urlStr = request.URL?.absoluteString
        
        let isRedirectURL:Bool = (urlStr?.hasPrefix(redirect_uri))!
        
        if !isRedirectURL//不是授权回调地址,让它加载
        {
            return true
        }
        else//是授权回调地址,不让它加载
        {
            //query是get请求?后面的东西
            let query = request.URL?.query
            //判断授权是否成功
            if query!.hasPrefix("code=")//此时点击的是授权
            {   //截取code=后面的的授权码
                let code = (query! as NSString).substringFromIndex(5)
                GKPrint("截取出来的code是:  \(code)")
                GKUserAccountViewModel.shareInstance.loadAccessToken(code, loadAccessTokenSucceedCallBack:
                { (error) in
                    
                        if error != nil
                        {
                            GKPrint("加载accessToken出错:\(error)")
                            SVProgressHUD.showErrorWithStatus("网络不给力")
                            
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { 
                                () -> Void in
                                self.cancel()
                            })
                            return
                        }
                        //成功了
                        GKPrint("加载token成功了")
                        self.cancel()
                    
                        //跳转到欢迎界面
                        let vc = GKWelcomeViewController()
                        (UIApplication.sharedApplication().delegate as! AppDelegate).switchViewController(vc)
                    })
                }
            else//此时点击的是取消
            {
                self.cancel()
            }
        }
        
        return false
    }
    

    
    
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        if error?.code == 102 {
            return//102:点击了取消
        }
        
        SVProgressHUD.showErrorWithStatus("网络不给力啊")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
    }
}

